﻿using System;
using System.Runtime.Caching;

namespace Common.Cache.Memory
{
    public class MemCache : IMemCache
    {
        public T GetFromCache<T>(string cacheKey, Func<T> getItemCallback, float timeCache = 10) where T : class //Default is 10 minute cache data
        {
            T item = MemoryCache.Default.Get(cacheKey) as T;
            if (item == null)
            {
                item = getItemCallback();
                MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(timeCache));
            }
            return item;
        }

        public void RemoveFromCache(string key, bool isApart = false)
        {
            key = key.Replace("{0}", string.Empty).Replace("{1}", string.Empty).Replace("{2}", string.Empty);
            if (!isApart)
                MemoryCache.Default.Remove(key);
            else
                foreach (var element in MemoryCache.Default)
                {
                    if (element.Key.StartsWith(key))
                        MemoryCache.Default.Remove(element.Key);
                }
        }
    }
}
